package com.sinosun.autotestmachine;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sinosun.autotestmachine.tools.TaskManager;
import com.sinosun.autotestmachine.tools.parser.ParamKey;
import com.sinosun.autotestmachine.tools.reader.NetCaseMaker;
import com.sinosun.autotestmachine.tools.reader.ReadMode;
import com.sinosun.autotestmachine.tools.reader.Status;
import com.sinosun.autotestmachine.tools.utils.RunningRecorder;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	List<String> showContent = new ArrayList<String>();
	ListView showText;
	Button btnStart;
	Button btnStop;
	Button btnPick;
	TextView txtTip;
	TextView timeTip;
	private ItemAdapter adapter;
	private String all = "all:";
	private String pass = ", pass:";
	private String failed = ", failed:";
	private String progress = ", progress:";
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    Runnable runnable;
	private long timeLong = 0;
	
	Handler mHandler = new Handler() {
		public void handleMessage(Message m) {
			if (m.what == App.TEST_RESULT) {
				Element e = (Element) m.obj;
				if (App.allInfo.size() == 0) {		//添加第一条数据
					App.allInfo.add(e);
				} else {				//添加的 caseId 已经存在
					if (App.allInfo.get(App.allInfo.size() - 1).getIndex() == e.getIndex() && App.allInfo.get(App.allInfo.size() - 1).getTaskId().equals(e.getTaskId())) {
						if (App.allInfo.get(App.allInfo.size() - 1).getEleFlag() == 0) {		//只有以前是正确状态时，才可以更改错误信息，否则保留最早的错误信息
							App.allInfo.get(App.allInfo.size() - 1).setEleFlag(e.getEleFlag());
						}
						App.allInfo.get(App.allInfo.size() - 1).setEndFlag(e.getEndFlag());
						String showStr = new String();
						if (!e.getEndFlag()) {
							showStr = App.allInfo.get(App.allInfo.size() - 1).getEleStr() + e.getEleStr();
						} else {
							String tmpStr = new String();
							if (App.allInfo.get(App.allInfo.size() - 1).getEleStr().endsWith(",")) {
								tmpStr = App.allInfo.get(App.allInfo.size() - 1).getEleStr().substring(0, App.allInfo.get(App.allInfo.size() - 1).getEleStr().length() - 1);
							} else {
								tmpStr = App.allInfo.get(App.allInfo.size() - 1).getEleStr();
							}
							showStr = tmpStr + "],\n\"" + ParamKey.CASE_RESULT + "\":" + App.allInfo.get(App.allInfo.size() - 1).getEleFlag()
									+ ",\n\"" + ParamKey.TASK_ID + "\":\"" + e.getTaskId() + "\"\n}";
							RunningRecorder.getRunningRecorder().record(showStr);		//每一个 case 运行结束，记录本次 case 的运行结果（不是实时记录）
							
							if (!TextUtils.isEmpty(e.getTaskId())) {	//如果 taskId 存在，即为网络任务
								JSONArray resJa = App.allNetWorkRet.get(e.getTaskId());
								if (resJa == null) {
									resJa = new JSONArray();
								}
								try {
									JSONObject jo = new JSONObject(showStr);
									resJa.put(jo);
								} catch (JSONException e1) {
									e1.printStackTrace();
								}
								App.allNetWorkRet.put(e.getTaskId(), resJa);
							}
						}
						App.allInfo.get(App.allInfo.size() - 1).setEleStr(showStr);
					} else {			//添加新的 caseId 不存在
						App.allInfo.add(e);
					}
				}
				
				adapter.notifyDataSetChanged();
				if (showText.getLastVisiblePosition() == adapter.getCount() - 1 || showText.getLastVisiblePosition() == adapter.getCount() - 2) {
					showText.setSelection(adapter.getCount() - 1);
				}
				
				int trueSize = 0;
				int falseSize = 0;
				for (Element ele : App.allInfo) {
					if (ele.getEleFlag() == 0 && ele.getEndFlag()) {
						trueSize++;
					}
					if (ele.getEleFlag() != 0 && !TextUtils.isEmpty(ele.getEleStr()) && ele.getEndFlag()) {
						falseSize++;
					}
				}
				txtTip.setText(all + TaskManager.getTaskManager().getLoopNumber() + progress + adapter.getCount() + pass + trueSize + failed + falseSize + ".");
				
			} else if (m.what == App.TEST_STOP_FLAG) {
				btnStop.setEnabled(false);
				btnStart.setEnabled(true);
				btnPick.setEnabled(true);
				stopTimer();
			} else if (m.what == App.TEST_START_FALG) {
				txtTip.setText(all + TaskManager.getTaskManager().getLoopNumber() + progress + 0 + pass + 0 + failed + 0 + ".");
				btnStop.setEnabled(true);
				btnStart.setEnabled(false);
				btnPick.setEnabled(false);
				startTimer();
			} else if (m.what == App.TEST_TIME_FRESH_FLAG) {
				long time = (long)m.obj;
				long min = time/60;
				long hour = time/3600;
				long sec = time%60;
				timeTip.setText(hour + ":" + min + ":" + sec);
			} else if (m.what == App.TEST_REPORT_RESULT_FLAG) {			//发送一个 task 的测试结果
				String taskId = (String) m.obj;
				if (App.allNetWorkRet.get(taskId) != null) {
					NetCaseMaker.reportTaskResult(taskId, "0", App.allNetWorkRet.get(taskId).toString(), "0");
					App.allNetWorkRet.remove(taskId);
				}
			} else if (m.what == App.TEST_REPORT_ALL_RESULT_FLAG) {		//清场动作，发送所有还在 task 的测试结果
				for (String taskIdEle : App.allNetWorkRet.keySet()) {
					NetCaseMaker.reportTaskResult(taskIdEle, "0", App.allNetWorkRet.get(taskIdEle).toString(), "0");
				}
				App.allNetWorkRet.clear();
			}
		}
	};

	@Override protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		showText = (ListView) findViewById(R.id.show);
		btnStart = (Button) findViewById(R.id.btn_start);
		btnStop = (Button) findViewById(R.id.btn_stop);
		btnPick = (Button) findViewById(R.id.btn_pick);
		txtTip = (TextView) findViewById(R.id.test_tip);
		timeTip = (TextView) findViewById(R.id.time_tip);
		adapter = new ItemAdapter(MainActivity.this, App.allInfo);
		showText.setAdapter(adapter);
		
		btnStart.setOnClickListener(clickListener);
		btnStop.setOnClickListener(clickListener);
		btnPick.setOnClickListener(clickListener);
		
		TaskManager.getTaskManager().setHandler(mHandler);
		TaskManager.getTaskManager().startTest();
		if (App.caseReadMode == ReadMode.NETWORK) {
			NetCaseMaker.reportDeviceStatus(Status.IDLE);
		}
		
	}
	
	private OnClickListener clickListener = new OnClickListener() {
		@Override public void onClick(View v) {
			switch(v.getId()) {
			case R.id.btn_start:
				App.allInfo.clear();
				adapter.notifyDataSetChanged();
				TaskManager.getTaskManager().startTest();
				break;
			case R.id.btn_stop:
				TaskManager.getTaskManager().stopTest();
				break;
			case R.id.btn_pick:
				Bundle bundle = new Bundle();
				bundle.putString(App.PATH, App.getInstance().getTestCasePath());
				Intent intent = new Intent(MainActivity.this, FileSelectActivity.class);
				intent.putExtras(bundle);
				MainActivity.this.startActivity(intent);
				break;
			}
		}
	};
	
	private void initTimingThread() {
		service = Executors.newSingleThreadScheduledExecutor();
		timeLong = 0;
        runnable = new Runnable() {  
            public void run() {  
            	timeLong++;
				Message msg = mHandler.obtainMessage();
				msg.what = App.TEST_TIME_FRESH_FLAG;
				msg.obj = timeLong;
				mHandler.sendMessage(msg); 
            }  
        };
	}
	
	private void startTimer() {
		initTimingThread();
		service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
	}
	
	private void stopTimer() {
		service.shutdown();
	}
			
}
